package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.AddressDao;
import com.rk.kbk.dao.SendTaskDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Address;
import com.rk.kbk.model.SendTask;
import com.rk.kbk.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @SendTaskController
 * @Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/sendTask")
public class SendTaskController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private SendTaskDao sendTaskDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AddressDao addressDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改
     * @param sendTask
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSendTask",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSendTask(@RequestBody SendTask sendTask){
        log.debug("添加/修改");
        sendTaskDao.save(sendTask);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改
     * @param sendTasks
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeSendTask",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeSendTask(@RequestBody List<SendTask> sendTasks){
        log.debug("批量添加/修改");
        sendTaskDao.save(sendTasks);
        return JsonResp.ok();
    }

    /**
     * @获取详情-BySendTaskId
     * @param sendTaskId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sendTaskDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findSendTaskDetailsBySendTaskId(Long sendTaskId) {
        log.debug("获取详情-BySendTaskId");
        return JsonResp.ok(sendTaskDao.findOne(sendTaskId));
    }

    /**
     * @分页查询(jpa方式)
     * @param sendTask 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageSendTaskJpa(@RequestBody(required = false) SendTask sendTask, Integer pageNum, Integer pageSize) {
        log.debug("分页查询(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == sendTask) {
            page = sendTaskDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  sendTask.getUserName();
            page = sendTaskDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<SendTask> content = page.getContent();
//        for (SendTask sendTask1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除-one(永久)
     * @param sendTaskId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSendTaskOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSendTaskOne(Long sendTaskId) {
        log.debug("删除-one(永久)");
        sendTaskDao.delete(sendTaskId);
        return JsonResp.ok();
    }

    /**
     * @批量删除(永久)
     * @param sendTasks
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeSendTask",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeSendTask(@RequestBody List<SendTask> sendTasks) {
        log.debug("批量删除(永久)");
        sendTaskDao.delete(sendTasks);
        return JsonResp.ok();
    }

    /**
     * @获取详情-ByAreaCode
     * @param areaCode
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sendTaskDetailsByAreaCode",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp sendTaskDetailsByAreaCode(String areaCode) {
        log.debug("获取详情-ByAreaCode");
        return JsonResp.ok(sendTaskDao.findByAreaCode(areaCode));
    }


    /**
     * @查看保存的区域内是否已存在
     * @param sendTask
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/checkSendTaskDetail",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp checkSendTaskDetail(@RequestBody SendTask sendTask){
        log.debug("查看保存的区域内是否已存在");
        SendTask sendTaskOld = sendTaskDao.findByAreaCode(sendTask.getAreaCode());
        if(sendTaskOld!=null){
            return JsonResp.fa("该区域已存在配送任务,是否确定更换？");
        }
        return  JsonResp.ok();
    }


    /**
     * @保存配送任务
     * @param sendTask
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/saveSendTask",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp saveSendTask(@RequestBody  SendTask sendTask){
        log.debug("保存配送任务");
        sendTask.setStatus(0);
        sendTaskDao.save(sendTask);
        return JsonResp.ok();
    }

    /**
     * @更新配送任务
     * @param sendTask
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/updateSendTaskDetail",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp updateSendTaskDetail(@RequestBody  SendTask sendTask){
        log.debug("更新配送任务");
        SendTask sendTaskOld=sendTaskDao.findByAreaCode(sendTask.getAreaCode());
        sendTaskOld.setDailyTasks(sendTask.getDailyTasks());
        sendTaskOld.setRestDays(sendTask.getRestDays());
        sendTaskOld.setOrderTicket(sendTask.getOrderTicket());
        sendTaskOld.setWorktimeMon(sendTask.getWorktimeMon());
        sendTaskOld.setWorktimeEve(sendTask.getWorktimeEve());
        sendTaskOld.setChangeDays(sendTask.getChangeDays());
        sendTaskDao.save(sendTaskOld);
        return  JsonResp.ok();
    }

    /**
     * @获取详情-ByUserId
     * @param userId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sendTaskDetailsByUserId",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp sendTaskDetailsByAreaCode(Long userId) {
        log.debug("获取详情-ByUserId");
        User user = userDao.findOne(userId);
        Address address = addressDao.findOne(user.getAddress());
        SendTask sendTask=sendTaskDao.findByAreaCode(address.getAreaCode());
        if(sendTask==null||sendTask.equals("")){
            return JsonResp.fa("该骑手注册地区未开通！");
        }else{
            return JsonResp.ok(sendTask);
        }
    }


}
